<?php

declare(strict_types=1);

namespace Api\Service\v1;

use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Service\LowQueueService;
use App\Robot\Dto\CommonJobDto;
use App\Robot\Job\CommonJob;
use App\Robot\Service\SendRobotMessageService;
use Hyperf\Di\Annotation\Inject;
use Mine\Exception\NormalStatusException;

class RobotMsgApiService
{
    #[Inject]
    protected ChRobotMapper $robotMapper;

    /**
     * 发送消息
     * @param array $params
     * @return bool
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function sendMsg(array $params): bool
    {
        $robotInfo = $this->robotMapper->findById($params['robot_id']);
        if(empty($robotInfo) || $robotInfo->main_uid != $params['uid']){
            throw new NormalStatusException('企微号信息错误');
        }

        if($robotInfo->login_status != 1){
            throw new NormalStatusException('请先扫码登录');
        }

        $contentList = json_decode($params['content'],true);
        $toId = $params['to_id'];
        $delayTime = 0;
        foreach ($contentList as $item){
            $messageData = [
                'robot_id' => $robotInfo->id,
                'to_id' => $toId,
                'msg_type' => $item['msg_type'],
                'content' => $item['content']
            ];
            $delayTime = $delayTime + mt_rand(2,3);
            container()->get(LowQueueService::class)->push(new CommonJob(new CommonJobDto(
                classname: SendRobotMessageService::class,
                method: 'handle',
                data: $messageData
            )),$delayTime);
        }
        return true;
    }
}